layui.use(["zlContext", "zltreemenu"], function (exports) {
    var $ = layui.$
        , zlContext = layui.zlContext
        , layer = layui.layer
        , table = layui.table
        , form = layui.form
        , zltreemenu = layui.zltreemenu
        , zlConfig = layui.zlConfig
        , statusName = zlConfig.global.result.statusName
        , msgName = zlConfig.global.result.msgName
        , dataName = zlConfig.global.result.dataName
        , OK = zlConfig.global.result.okState
        , fullheight = 'full-30'
        , loadingLayer;

    var options = {
        float: false,
        auto: true,
        always_show_resize_handle: true
    };
    var frmTemplate = [
        '<div>'
        , '  <div class="grid-stack-item-content">'
        , '     <div class="grid-stack-item-header"><h5 class="item-title">标题</h5>'
        , '         <div class="grid-stack-item-operate">'
        , '             <button class="layui-btn layui-btn-primary layui-btn-sm edit-btn"><i class="layui-icon layui-icon-edit"></i></button>'
        , '             <button class="layui-btn layui-btn-primary layui-btn-sm del-btn"><i class="layui-icon layui-icon-delete"></i></button>'
        , '         </div>'
        , '     </div>'
        , '     <div class="grid-stack-item-body"></div>'
        , '  </div>'
        , '</div>'
    ];
    var defaultNode = {
        x: 0,
        y: 0,
        width: 4,
        height: 8
    }

    //渲染
    $('.grid-stack').gridstack(options);

    var gridstackAction = new function () {
        this.items = [];
        this.grid = $('.grid-stack').data('gridstack');

        //增加
        this.addNewWidget = function () {
            var node = this.items.pop() || {
                x: 0,
                y: 0,
                width: 4,
                height: 8
            };
            this.grid.addWidget($(frmTemplate.join("")),
                node.x, node.y, node.width, node.height);
            return false;
        }.bind(this);

        //清空
        this.clearGrid = function () {
            this.grid.removeAll();
            return false;
        }.bind(this);

        //保存
        this.saveGrid = function () {
            var selector = '.grid-stack > .' + (options.itemClass ? options.itemClass : 'grid-stack-item') + ':visible';
            var resIds = [];
            this.serializedData = _.map($(selector), function (el) {
                var $el = $(el);
                var node = $el.data('_gridstack_node');
                var data = {};
                if (typeof node.id != 'undefined') {
                    data['id'] = node.id;
                }
                if (typeof node.x != 'undefined') {
                    data['x'] = node.x;
                }
                if (typeof node.y != 'undefined') {
                    data['y'] = node.y;
                }
                if (typeof node.width != 'undefined') {
                    data['width'] = node.width;
                }
                if (typeof node.height != 'undefined') {
                    data['height'] = node.height;
                }
                if (typeof node.minWidth != 'undefined') {
                    data['minWidth'] = node.minWidth;
                }
                if (typeof node.maxWidth != 'undefined') {
                    data['maxWidth'] = node.maxWidth;
                }
                if (typeof node.minHeight != 'undefined') {
                    data['minHeight'] = node.minHeight;
                }
                if (typeof node.maxHeight != 'undefined') {
                    data['maxHeight'] = node.maxHeight;
                }
                if (typeof node.locked != 'undefined') {
                    data['locked'] = node.locked;
                }
                if (typeof node.noMove != 'undefined') {
                    data['noMove'] = node.noMove;
                }
                if (typeof node.noResize != 'undefined') {
                    data['noResize'] = node.noResize;
                }
                if (typeof node.autoPosition != 'undefined') {
                    data['autoPosition'] = node.autoPosition;
                }
                data['zlRwid'] = $el.find('.grid-stack-item-content').attr('data-zl-rwid');
                data['titleName'] = $el.find('.grid-stack-item-content .grid-stack-item-header .item-title').text();
                data['isshow'] = $el.find('.grid-stack-item-content .grid-stack-item-header .item-title').attr('isshow');
                return data;

            }, this);
            var content = this.serializedData;
            var params = {
                "RWID": $('.layui-hide input[name=RWID]').val(),
                "HP_CONTENT": JSON.stringify(content)
            }
            loadingLayer = layer.msg('数据保存中，请稍候...', { icon: 16, time: false, shade: 0.1 });
            zlContext.post(layui.cache['contentPath'] + '/manager/corehomepage/hpcontent/modify', params, function (result) {
                if (result[statusName] = OK) {
                    zlContext.successMsg('保存成功');
                } else {
                    zlContext.errorMsg(result[msgName]);
                }
                layer.close(loadingLayer);
            });

        }.bind(this);

        $('#add-new-widget').click(this.addNewWidget);

        $('.design-header #btn-clear').click(this.clearGrid);

        $('.design-header #btn-save').click(this.saveGrid);

        $('.design-header #btn-preview').click(function () {
            var objName = $('.layui-hide input[name=OBJNAME]').val();
            layer.open({
                type: 1,
                maxmin: true,
                title: objName + '-首页预览',
                id: 'formPreview',
                area: ['100%', '100%'],
                // method: "post",
                content: $('.grid-stack'),
                success: function () {
                    $('.grid-stack-item-operate .layui-btn').hide();
                    var grid=$('.grid-stack').gridstack(options).data('gridstack');
                    grid.movable('.grid-stack-item', false);
                    grid.resizable('.grid-stack-item', false);
                    // grid.dd.draggable('.grid-stack-item',{scroll:true});
                    // var newoptions = {
                    //     float: false,
                    //     auto: true,
                    //     always_show_resize_handle: true,
                    //     disableDrag: true,
                    //     disableResize: true,
                    // };
                    // $('.grid-stack').data('gridstack',false);
                    // $('.grid-stack').gridstack(newoptions);                   
                    $('.item-title').each(function (index) {
                        var ishow = $(this).attr('isshow');
                        if (ishow == '0') {
                            $(this).parents('.grid-stack-item-header').hide();
                            $(this).parents('.grid-stack-item-content').find('.grid-stack-item-body').css('top', 0);
                        }
                    });
                },
                cancel: function () {
                    $('.grid-stack-item-operate .layui-btn').show();
                    var grid = $('.grid-stack').gridstack(options).data('gridstack');
                    grid.movable('.grid-stack-item', true);
                    grid.resizable('.grid-stack-item', true);
                    $('.grid-stack-item-header').show();
                    $('.grid-stack-item-body').css('top', 41);
                }

                // params: { "RWID": $('.layui-hide input[name=RWID]').val() },
            });
        })

        $(".grid-stack").on('click', ".grid-stack-item-content .grid-stack-item-operate .del-btn", function () {
            var $delItem = $(this).parents('.grid-stack-item');
            gridstackAction.grid.removeWidget($delItem);
        });

        $(".grid-stack").on('click', ".grid-stack-item-content .grid-stack-item-operate .edit-btn", function () {
            var $editItem = $(this).parents('.grid-stack-item');
            gridAction.editTitleGrid($editItem);
        });
    }

    var gridAction = {
        curEditItem: undefined,
        resAuthTree: undefined,
        editTitleGrid: function ($item) {
            var frmTitleLayer = [
                '<div class="site-text site-block" style="border:none;padding-bottom:10px">'
                , ' <form class="layui-form"  action="">'
                , '     <div class="layui-form-item" id="layer-item-title">'
                , '         <div class="layui-inline">'
                , '             <label class="layui-form-label">标题名称:</label>'
                , '	            <div class="layui-input-block">'
                , '                 <input type="text" lay-verify="required" name="item-title"  class="layui-input" maxlength="80">'
                , '	            </div>'
                , '         </div>'
                , '     </div>'
                , '     <div class="layui-form-item" id="layer-item-title-show">'
                , '         <div class="layui-inline">'
                , '             <label class="layui-form-label" style="width:auto">标题栏是否显示（设计期无效）:</label>'
                , '	            <div class="layui-input-block">'
                , '                 <input type="checkbox" name="item-show" valueformat="1|0" lay-filter="itemshow" lay-text="显示|隐藏" lay-skin="switch" checked="checked">'
                , '	            </div>'
                , '         </div>'
                , '     </div>'
                , ' </form>'
                , '</div>'
            ],
                $itemtile = $item.find('.grid-stack-item-header .item-title'),
                itemshowvalue = $itemtile.attr("isshow");
            layer.open({
                type: 1
                , id: 'itemTitleLayer'
                , title: "编辑标题"
                , area: ["420px", "240px"]
                , content: frmTitleLayer.join('')
                , btn: ['确定', '取消']
                , success: function () {
                    gridAction.curEditItem = $item;
                    var title = $itemtile.text();
                    if (itemshowvalue == '0') {
                        $('input[name="item-show"]').prop('checked', '');
                    }
                    $("#itemTitleLayer #layer-item-title input[name=item-title]").val(title);
                    form.render();
                    form.on('switch(itemshow)', function (data) {
                        itemshowvalue = $('input[name="item-show"]').prop('checked');
                    });
                }
                , yes: function (index, layero) {
                    var title = $("#itemTitleLayer #layer-item-title input[name=item-title]").val();
                    if (!title || !$.trim(title)) {
                        layer.msg('必填项不能为空!', { icon: 5, shift: 6 });
                        return false;
                    }
                    $itemtile.text(title);
                    $itemtile.attr('isshow', itemshowvalue ? 1 : 0);
                    layer.close(index);
                }
            });
        },
        resTreeGrid: function () {
            loadingLayer = layer.msg('数据加载中，请稍候...', { icon: 16, time: false, shade: 0.1 });
            layer.open({
                type: 1
                , id: 'resTreeLayer'
                , title: "选择首页模块"
                , area: ["800px", "680px"]
                , content: $('#resTreeContainer')
                , btn: ['确定', '取消']
                , success: function () {
                    layer.close(loadingLayer);
                }
                , yes: function (index, layero) {
                    var nodes = gridAction.resAuthTree.getCheckedNodes(true);
                    if (nodes) {
                        if (nodes.length > 10) {
                            zlContext.warnMsg("选择的个数不能大于10");
                            return false;
                        }
                        $.each(nodes, function (i, node) {
                            var url = node['RES_ACTION'],
                                resId = node['RES_ID'];
                            var titleName = node['OBJNAME'];
                            if (url != null) {
                                url = url.replace(/#{contentpath}/i, layui.cache['contentPath']);
                            }
                            if (titleName && titleName.indexOf('-[') != -1) {
                                titleName = titleName.substring(0, titleName.indexOf('-['));

                            }
                            var $item = $(frmTemplate.join(''));
                            $item.find('.grid-stack-item-content').attr('data-zl-rwid', resId);
                            $item.find('.grid-stack-item-content').css('height', '100%');
                            $item.find('.grid-stack-item-header .item-title').text(titleName);
                            $item.find('.grid-stack-item-body').css("height", "calc(100% - 41px)");
                            $item.find('.grid-stack-item-body').append('<iframe src="' + url + '" width=100% height=100%></iframe>');

                            var mod = i % 3;
                            gridstackAction.grid.addWidget($item, defaultNode.x + defaultNode.width * mod, defaultNode.y, defaultNode.width, defaultNode.height);
                        });
                    }
                    gridAction.resAuthTree.checkAllNodes(false);
                    //收缩
                    gridAction.resAuthTree.expandAll(false);
                    layer.close(index);
                }
                , btn2: function (index, layero) {
                    gridAction.resAuthTree.checkAllNodes(false);
                    //收缩
                    gridAction.resAuthTree.expandAll(false);
                }
                , cancel: function (index, layero) {
                    gridAction.resAuthTree.checkAllNodes(false);
                    //收缩
                    gridAction.resAuthTree.expandAll(false);
                }
            });
        },
        initResTree: function () {
            gridAction.resAuthTree = zltreemenu.render('resAuthTree', {
                checkEnable: true,
                autoCheckTrigger: true,
                chkboxType: { "Y": "ps", "N": "s" },
                radioType: "all",
                dataurl: layui.cache['contentPath'] + "/manager/corehomepage/modules",
                type: "get",
                idKey: "RESRWID",
                search: false,
                dataFilter: function (treeId, parentNode, responseData) {
                    if (responseData[statusName] == OK) {
                        var data = responseData[dataName];
                        for (var i = 0; i < data.length; i++) {
                            if (data[i].RES_TYPE == "4C5CE7CCD7124C448A82E65B965B36CC") {
                                data[i].icon = layui.cache['contentPath'] + "/static/image/menud.png";
                                data[i].chkDisabled = true;
                            } else if (data[i].RES_TYPE == "D0F4A751E3654AB3A714B8A0309D0BCB") {
                                data[i].icon = layui.cache['contentPath'] + "/static/image/menu.png";
                            } else if (data[i].RES_TYPE == "EB7113E02DA643D3B800A03ED2D87C09") {
                                data[i].icon = layui.cache['contentPath'] + "/static/image/hidemenu.png";
                                if (!data[i].RES_ACTION) {
                                    data[i].chkDisabled = true;
                                }
                            }
                            if (data[i].BEIZ != "") {
                                data[i].OBJNAME = data[i].OBJNAME + '(' + data[i].BEIZ + ')' + '-[' + data[i].RESTYPENAME + ']';
                            } else {
                                data[i].OBJNAME = data[i].OBJNAME + '-[' + data[i].RESTYPENAME + ']';
                            }
                        }
                        return data;
                    }
                    else {
                        zlContext.errorMsg(responseData[msgName]);
                    }
                    return responseData;
                }
            }, {});
        }
    }

    var homepageRender = {
        content: undefined,
        resAuthMap: undefined,
        queryContentById: function (rwid) {
            var url = layui.cache['contentPath'] + '/manager/corehomepage/querybyid';
            var params = {
                'RWID': rwid
            }
            zlContext.asyncGet(url, params, function (result) {
                if (result[statusName] == OK) {
                    var obj = result[dataName];
                    homepageRender.resAuthMap = obj['RESAUTHMAP'] || {};
                    if (obj) {
                        if (obj['HP_CONTENT']) {
                            homepageRender.content = JSON.parse(obj['HP_CONTENT']);
                        }
                        $('.layui-hide input[name="OBJNAME"]').val(obj['OBJNAME']);
                    }
                } else {
                    zlContext.errorMsg(result[msgName]);
                }
            }, false);
        },
        render: function () {
            //内容不存在
            if (!homepageRender.content) {
                return;
            }
            var noAuthTemplate = [
                '<div class="empty-data" style="text-align:center;padding-top: 20px;font-size: 25px;color: #ccc;font-family: tahoma ,微软雅黑;">'
                , '  <div class="no-data-show" style="padding-top: 10px;font-size: 22px;">无权限访问</div>'
                , '</div>'
            ];
            $.each(homepageRender.content, function (index, node) {
                var rwid = node['zlRwid'];
                var titleName = node['titleName'] || '标题';
                var $item = $(frmTemplate.join(''));
                if (typeof node.locked != 'undefined') {
                    $item.attr('data-gs-locked', node.locked);
                }
                if (typeof node.noMove != 'undefined') {
                    $item.attr('data-gs-no-move', node.noMove);
                }
                if (typeof node.noResize != 'undefined') {
                    $item.attr('data-gs-no-resize', node.noResize);
                }
                $item.find('.grid-stack-item-content').attr('data-zl-rwid', rwid);
                $item.find('.grid-stack-item-header .item-title').text(titleName);
                $item.find('.item-title').attr('isshow', node.isshow);
                //权限判断
                var action = homepageRender.resAuthMap[rwid];
                var $itemBody = undefined;
                if (action && action != '1') {
                    var url = action.replace(/#{contentpath}/i, layui.cache['contentPath']);
                    $itemBody = $('<iframe src="' + url + '" width=100% height=100%></iframe>');
                } else {
                    $itemBody = $(noAuthTemplate.join(''));
                    if ("1" == action) {
                        $itemBody.find('.no-data-show').text('无效模块');
                    }
                }
                if(node['isshow']=='0'){
                    $item.find('.grid-stack-item-body').css("height","100%");
                }else{
                    $item.find('.grid-stack-item-body').css("height","calc(100% - 41px)");
                }
                $item.find('.grid-stack-item-body').append($itemBody);
                gridstackAction.grid.addWidget($item, node['x'], node['y'], node['width'], node['height'],
                    node['autoPosition'], node['minWidth'], node['maxWidth'], node['minHeight'], node['maxHeight'], node['id']);

            });
        }
    }

    loadingLayer = layer.msg('数据加载中，请稍候...', { icon: 16, time: false, shade: 0.1 });
    //初始化资源树
    gridAction.initResTree();
    //获取数据
    homepageRender.queryContentById($('.layui-hide input[name="RWID"]').val());
    //渲染
    homepageRender.render();
    layer.close(loadingLayer);
    //展示资源树
    $('.design-header #btn-add').click(function () {
        gridAction.resTreeGrid();
    });

    // z自适应控制页面高度
    $(window).resize(function () {
        var height = $(window).height() - 63;
        // $("body").css("min-height", $(window).height() - 90);
        // $(".grid-stack").css({ "height": height, "min-height": $(window).height() - 140 });
        // $(".sidebar-nav").css({ "height": $(window).height(), "min-height": $(window).height() - 65 })
    });
});